<?php

namespace App\Http\Requests;

class Curl
{

    protected $cache;

    public function __construct($cache = '')
    {
        if (!empty($cache)) {
            $this->cache = $cache;
        } else {
            $this->cache = 'uploads/';
        }

    }


    public function setCache($cache = '')
    {
        if (!empty($cache))
            $this->cache = $cache;
    }


    public function getFile($url, $fn, $error = 777)
    {
        $path = $this->buildFolder($this->cache);
        if ($path == false) return $error;

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
        $file = curl_exec($curl);

        curl_close($curl);

        //$filename = $this->cache.date("YmdHis");
        $filename = $this->cache . $fn;

        if (self::buildFile($file, $filename) == false)
            return false;

        return $filename;
    }


    public function buildFolder($dir)
    {
        if (!is_dir($dir)) {

            if (!mkdir($dir, 0777, TRUE) || !chmod($dir, 0777))
                return false;
        }

        return true;
    }


    public function moveFile($cache, $filename)
    {
        $file = @file_get_contents($cache);
        if (self::buildFile($file, $filename) == false)
            return false;

        unlink($cache);

        return $filename;
    }


    protected static function buildFile($file, $filename)
    {
        $write = @fopen($filename, "w");

        if ($write == false)
            return false;

        if (fwrite($write, $file) == false)
            return false;

        if (fclose($write) == false)
            return false;

        return true;
    }

}     